<template>
  <div class="error-analysis-container">
    <div class="analysis-header">
      <h3>错题分析</h3>
      <div class="filter-controls">
        <el-select v-model="selectedSubject" placeholder="选择科目" style="width: 150px; margin-right: 10px;">
          <el-option label="全部科目" value="" />
          <el-option label="数学" value="math" />
          <el-option label="语文" value="chinese" />
          <el-option label="英语" value="english" />
          <el-option label="物理" value="physics" />
          <el-option label="化学" value="chemistry" />
        </el-select>
        
        <el-select v-model="selectedDifficulty" placeholder="难度等级" style="width: 150px; margin-right: 10px;">
          <el-option label="全部难度" value="" />
          <el-option label="简单" value="easy" />
          <el-option label="中等" value="medium" />
          <el-option label="困难" value="hard" />
        </el-select>
        
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px; margin-right: 10px;"
        />
        
        <el-button type="primary" @click="filterErrors">筛选</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </div>
    </div>
    
    <!-- 统计概览 -->
    <div class="statistics-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ totalErrors }}</div>
              <div class="stat-label">总错题数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ reviewedErrors }}</div>
              <div class="stat-label">已复习</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ masteredErrors }}</div>
              <div class="stat-label">已掌握</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ Math.round((masteredErrors / totalErrors) * 100) || 0 }}%</div>
              <div class="stat-label">掌握率</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 错题列表 -->
    <div class="error-list-container">
      <el-table :data="errorList" stripe style="width: 100%">
        <el-table-column prop="question" label="题目" min-width="300">
          <template #default="scope">
            <div class="question-content">
              {{ scope.row.question }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="subject" label="科目" width="100">
          <template #default="scope">
            <el-tag :type="getSubjectTagType(scope.row.subject)">
              {{ getSubjectLabel(scope.row.subject) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="100">
          <template #default="scope">
            <el-tag :type="getDifficultyTagType(scope.row.difficulty)">
              {{ getDifficultyLabel(scope.row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="errorCount" label="错误次数" width="100" />
        <el-table-column prop="lastErrorTime" label="最近错误时间" width="150">
          <template #default="scope">
            {{ formatDate(scope.row.lastErrorTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" type="primary" @click="reviewQuestion(scope.row)">
              复习
            </el-button>
            <el-button size="small" type="success" @click="markAsMastered(scope.row)">
              标记掌握
            </el-button>
            <el-button size="small" type="danger" @click="deleteError(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalItems"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 错题详情对话框 -->
    <el-dialog v-model="dialogVisible" title="错题详情" width="60%">
      <div v-if="selectedQuestion" class="question-detail">
        <div class="question-section">
          <h4>题目</h4>
          <div class="question-text">{{ selectedQuestion.question }}</div>
        </div>
        
        <div class="answer-section">
          <h4>你的答案</h4>
          <div class="wrong-answer">{{ selectedQuestion.userAnswer }}</div>
        </div>
        
        <div class="correct-section">
          <h4>正确答案</h4>
          <div class="correct-answer">{{ selectedQuestion.correctAnswer }}</div>
        </div>
        
        <div class="analysis-section">
          <h4>解析</h4>
          <div class="analysis-text">{{ selectedQuestion.analysis }}</div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="reviewQuestion(selectedQuestion)">
          重新练习
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 状态管理
const selectedSubject = ref('')
const selectedDifficulty = ref('')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const totalItems = ref(0)
const dialogVisible = ref(false)
const selectedQuestion = ref(null)

// 统计数据
const totalErrors = ref(45)
const reviewedErrors = ref(32)
const masteredErrors = ref(28)

// 错题列表
const errorList = ref([
  {
    id: 1,
    question: '已知函数f(x) = x² + 2x - 3，求f(x)的最小值',
    subject: 'math',
    difficulty: 'medium',
    errorCount: 3,
    lastErrorTime: '2023-11-01 14:30:00',
    status: 'reviewing',
    userAnswer: 'f(x)的最小值为-4',
    correctAnswer: 'f(x)的最小值为-4，当x=-1时取得',
    analysis: '这是一个二次函数求最小值的问题。对于函数f(x) = ax² + bx + c，当a>0时，函数在x=-b/(2a)处取得最小值。本题中a=1，b=2，所以x=-2/(2×1)=-1，f(-1)=(-1)²+2×(-1)-3=1-2-3=-4。'
  },
  {
    id: 2,
    question: '下列哪个选项不是英语中的连词？',
    subject: 'english',
    difficulty: 'easy',
    errorCount: 2,
    lastErrorTime: '2023-11-02 09:15:00',
    status: 'mastered',
    userAnswer: 'because',
    correctAnswer: 'quickly',
    analysis: '连词是用来连接词、短语或句子的词。because是连词，而quickly是副词，不是连词。常见的连词有and, but, or, so, because等。'
  },
  {
    id: 3,
    question: '水的化学式是什么？',
    subject: 'chemistry',
    difficulty: 'easy',
    errorCount: 1,
    lastErrorTime: '2023-11-03 16:45:00',
    status: 'new',
    userAnswer: 'HO',
    correctAnswer: 'H₂O',
    analysis: '水分子由两个氢原子和一个氧原子组成，化学式为H₂O。每个氢原子提供1个电子，氧原子需要2个电子达到稳定结构，因此形成共价键。'
  },
  {
    id: 4,
    question: '一个物体从静止开始自由落体，3秒后的速度是多少？（g=10m/s²）',
    subject: 'physics',
    difficulty: 'medium',
    errorCount: 4,
    lastErrorTime: '2023-11-04 11:20:00',
    status: 'reviewing',
    userAnswer: '20m/s',
    correctAnswer: '30m/s',
    analysis: '自由落体运动的速度公式为v = gt，其中g是重力加速度，t是时间。本题中g=10m/s²，t=3s，所以v = 10×3 = 30m/s。'
  },
  {
    id: 5,
    question: '"春眠不觉晓"的下一句是什么？',
    subject: 'chinese',
    difficulty: 'easy',
    errorCount: 2,
    lastErrorTime: '2023-11-05 08:30:00',
    status: 'mastered',
    userAnswer: '处处闻啼鸟',
    correctAnswer: '处处闻啼鸟',
    analysis: '这是唐代诗人孟浩然的《春晓》中的诗句。全诗为：春眠不觉晓，处处闻啼鸟。夜来风雨声，花落知多少。'
  }
])

// 筛选错题
const filterErrors = () => {
  // 这里可以调用API进行筛选
  ElMessage.success('筛选条件已应用')
  loadErrorList()
}

// 重置筛选
const resetFilter = () => {
  selectedSubject.value = ''
  selectedDifficulty.value = ''
  dateRange.value = []
  currentPage.value = 1
  loadErrorList()
}

// 加载错题列表
const loadErrorList = async () => {
  try {
    // 这里可以调用API获取错题列表
    // const response = await getErrorList({
    //   subject: selectedSubject.value,
    //   difficulty: selectedDifficulty.value,
    //   startDate: dateRange.value[0],
    //   endDate: dateRange.value[1],
    //   page: currentPage.value,
    //   size: pageSize.value
    // })
    // errorList.value = response.data.list
    // totalItems.value = response.data.total
  } catch (err) {
    console.log('获取错题列表失败:', err)
  }
}

// 复习题目
const reviewQuestion = (question) => {
  selectedQuestion.value = question
  dialogVisible.value = true
}

// 标记为已掌握
const markAsMastered = async (question) => {
  try {
    // 这里可以调用API标记为已掌握
    // await markErrorAsMastered(question.id)
    question.status = 'mastered'
    masteredErrors.value++
    ElMessage.success('已标记为掌握')
  } catch (err) {
    console.log('标记掌握失败:', err)
  }
}

// 删除错题
const deleteError = async (question) => {
  try {
    await ElMessageBox.confirm('确定要删除这道错题吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里可以调用API删除错题
    // await deleteErrorQuestion(question.id)
    
    const index = errorList.value.findIndex(item => item.id === question.id)
    if (index !== -1) {
      errorList.value.splice(index, 1)
      totalErrors.value--
      if (question.status === 'mastered') {
        masteredErrors.value--
      }
    }
    
    ElMessage.success('错题已删除')
  } catch (err) {
    if (err !== 'cancel') {
      console.log('删除错题失败:', err)
    }
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadErrorList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadErrorList()
}

// 辅助函数
const getSubjectTagType = (subject) => {
  const typeMap = {
    math: '',
    chinese: 'success',
    english: 'warning',
    physics: 'danger',
    chemistry: 'info'
  }
  return typeMap[subject] || ''
}

const getSubjectLabel = (subject) => {
  const labelMap = {
    math: '数学',
    chinese: '语文',
    english: '英语',
    physics: '物理',
    chemistry: '化学'
  }
  return labelMap[subject] || subject
}

const getDifficultyTagType = (difficulty) => {
  const typeMap = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return typeMap[difficulty] || ''
}

const getDifficultyLabel = (difficulty) => {
  const labelMap = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return labelMap[difficulty] || difficulty
}

const getStatusTagType = (status) => {
  const typeMap = {
    new: 'info',
    reviewing: 'warning',
    mastered: 'success'
  }
  return typeMap[status] || ''
}

const getStatusLabel = (status) => {
  const labelMap = {
    new: '新错题',
    reviewing: '复习中',
    mastered: '已掌握'
  }
  return labelMap[status] || status
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  loadErrorList()
})
</script>

<style scoped>
.error-analysis-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.analysis-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.analysis-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.filter-controls {
  display: flex;
  align-items: center;
}

.statistics-overview {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.stat-content {
  padding: 10px;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.error-list-container {
  margin-top: 20px;
}

.question-content {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.question-detail {
  padding: 10px 0;
}

.question-section,
.answer-section,
.correct-section,
.analysis-section {
  margin-bottom: 20px;
}

.question-section h4,
.answer-section h4,
.correct-section h4,
.analysis-section h4 {
  margin-bottom: 10px;
  color: #303133;
  font-weight: 600;
}

.question-text {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 16px;
  line-height: 1.5;
}

.wrong-answer {
  padding: 15px;
  background-color: #fef0f0;
  border-radius: 4px;
  color: #f56c6c;
  border-left: 4px solid #f56c6c;
}

.correct-answer {
  padding: 15px;
  background-color: #f0f9ff;
  border-radius: 4px;
  color: #409eff;
  border-left: 4px solid #409eff;
}

.analysis-text {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
}
</style>